package com.appspot.inkisapi.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Text;

public class LowLevelDatastoreService {
	private static DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();

	public static void createOrUpdateEntity(String kind, String identifier,
			Map<String, Object> properties) {
		Key key = KeyFactory.createKey(kind, identifier);
		Entity entity;
		try {
			entity = datastore.get(key);
		} catch (EntityNotFoundException e) {
			entity = null;
		}
		if (entity == null) {
			entity = new Entity(kind, identifier);
		}
		Iterator iterator = properties.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry pairs = (Map.Entry) iterator.next();
			entity.setProperty(pairs.getKey().toString(), new Text(pairs
					.getValue().toString()));
		}
		datastore.put(entity);
	}

	public static Entity getEntity(String kind, String identifier) {
		Key key = KeyFactory.createKey(kind, identifier);
		try {
			return datastore.get(key);
		} catch (EntityNotFoundException e) {
			return null;
		}
	}

	public static Iterable<Entity> getEntities(String kind, String searchBy,
			String searchFor) {
		Query q = new Query(kind);
		if (searchFor != null && !"".equals(searchFor)) {
			q.addFilter(searchBy, FilterOperator.EQUAL, searchFor);
		}
		PreparedQuery pq = datastore.prepare(q);
		return pq.asIterable();
	}

	public static boolean deleteEntity(String kind, String identifier) {
		Key key = KeyFactory.createKey(kind, identifier);
		Query query = new Query();
		Key parentKey = KeyFactory.createKey(kind, identifier);
		query.setAncestor(parentKey);
		query.addFilter(Entity.KEY_RESERVED_PROPERTY,
				Query.FilterOperator.GREATER_THAN, parentKey);
		List<Entity> items = datastore.prepare(query).asList(
				FetchOptions.Builder.withDefaults());
		if (!items.isEmpty()) {
			return false;
		}
		datastore.delete(key);
		return true;
	}
}